package com.zwjstudy.cachestudy.redis7.jedis.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * ClassName: RedisConfig
 * Package: com.zwjstudy.cachestudy.redis7.jedis.config
 * Description:
 *
 * @Author: 张文俊
 * @Create: 2025-09-12 - 10:25
 * @Version: v1.0
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // 设置 key 的序列化器为 String 序列化器
        template.setKeySerializer(new StringRedisSerializer());
        // 设置 value 的序列化器为 Jackson2JsonRedisSerializer（或其他你喜欢的JSON序列化器）
        // 以下示例使用 Jackson2JsonRedisSerializer 来序列化值对象为 JSON 字符串
         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
         template.setValueSerializer(jackson2JsonRedisSerializer);

        // 为了方便演示，这里值也先用 String 序列化器，适合存储字符串值
//        template.setValueSerializer(new StringRedisSerializer());

        // 设置 hash key 和 value 的序列化器
        template.setHashKeySerializer(new StringRedisSerializer());
//        template.setHashValueSerializer(new StringRedisSerializer()); // 或者使用 Jackson2JsonRedisSerializer
        template.setHashValueSerializer(jackson2JsonRedisSerializer); // 或者使用 Jackson2JsonRedisSerializer

        template.afterPropertiesSet();
        return template;
    }

}
